package com.lxyblog2030.blog.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxyblog2030.blog.pojo.Type;
import com.lxyblog2030.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class TypeController {

   @Autowired
  private TypeService typeService;
    @GetMapping("/types")
    public String list(Model model, @RequestParam (defaultValue = "1",value = "pageNum") Integer pageNum){
    PageHelper.startPage(pageNum,3);
    List<Type> adminTypes = typeService.getAdminType();
    PageInfo<Type> pageInfo = new PageInfo<>(adminTypes);
    model.addAttribute("pageInfo",pageInfo);
    return "admin/types";
}
//跳转到新增页面
@GetMapping("/types/input")
public String toAdd(){
        return "admin/types-input";
}

//处理新增请求
@PostMapping("/types/add")
public String Add(Type type, RedirectAttributes attributes){

    Type type1 = typeService.getTypeByName(type.getName());
    if (type1!=null){
        attributes.addFlashAttribute("message","不能添加重复的类");
        return "redirect:/admin/types/input";
    }
    typeService.saveType(type);
    attributes.addFlashAttribute("message","添加成功");
    return "redirect:/admin/types";


}
//跳转更新页面
@GetMapping("/types/{id}/input")
public String editInput(@PathVariable long id,Model model){
    Type type = typeService.getType(id);
    model.addAttribute("type",type);

    return "admin/types-update";
}

//处理更新请求
    @PostMapping("/types/update")
    public String editPost(Type type,RedirectAttributes redirectAttributes){
        typeService.updateType(type);
        redirectAttributes.addFlashAttribute("message","修改成功");
        return "redirect:/admin/types";
}


//处理删除请求
@GetMapping("/types/{id}/delete")
public String delete(@PathVariable long id,RedirectAttributes redirectAttributes){
        if (typeService.getType(id)!=null){
            typeService.deleteType(id);
            redirectAttributes.addFlashAttribute("message","删除成功");
        }else {
            redirectAttributes.addFlashAttribute("message","信息不存在请重新确认");
        }
        return "redirect:/admin/types";

}

}
